package org.theta.framework.dal.mybatis.typehandler.sqlite;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.theta.framework.core.utils.DateUtils;
import static org.theta.framework.core.utils.DateUtils.*;

@MappedTypes({ Date.class })
public class EnDateTypeHandler extends BaseTypeHandler<Date> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, DateUtils.format(parameter, FORMAT_NORMAL));
	}

	@Override
	public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String dateStr = rs.getString(columnName);
		return dateStr == null ? null : DateUtils.parse(dateStr, FORMAT_NORMAL);
	}

	@Override
	public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String dateStr = rs.getString(columnIndex);
		return dateStr == null ? null : DateUtils.parse(dateStr, FORMAT_NORMAL);
	}

	@Override
	public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String dateStr = cs.getString(columnIndex);
		return dateStr == null ? null : DateUtils.parse(dateStr, FORMAT_NORMAL);
	}

}
